package wangjg.android.media.h264;

import java.io.File;
import java.io.RandomAccessFile;

import android.hardware.Camera;
import android.util.Log;

public class EncoderPreviewCallback implements Camera.PreviewCallback {
	private Encoder encoder = new Encoder();
	private RandomAccessFile raf = null;
	private byte[] h264Buff = null;

	public EncoderPreviewCallback(int width, int height) {
		encoder.init(width, height);
		h264Buff = new byte[width * height * 8];
		try {
			File file = new File("/sdcard/camera.h264");
			raf = new RandomAccessFile(file, "rw");
		} catch (Exception ex) {
			Log.v("System.out", ex.toString());
		}

	}

	protected void finalize() {
		encoder.release();
		if (null != raf) {
			try {
				raf.close();
			} catch (Exception ex) {
				Log.v("System.out", ex.toString());
			}
		}
		try {
			super.finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public void onPreviewFrame(byte[] data, Camera camera) {
		int result = encoder.encode(-1, data, data.length, h264Buff);
		try {
			if (result > 0)
				raf.write(h264Buff, 0, result);
		} catch (Exception ex) {
			Log.v("System.out", ex.toString());
		}
	}

}